import Foundation

class UserDefaultsManager {
    static let shared = UserDefaultsManager()
    
    private init() {}
    
    // 保存String值
    func setString(_ value: String, forKey key: String) {
        UserDefaults.standard.set(value, forKey: key)
    }
    
    func getString(forKey key: String) -> String? {
        let value = UserDefaults.standard.string(forKey: key)
        return value ?? "null"
    }
    
    func setInt(_ value: Int, forKey key: String) {
        UserDefaults.standard.set(value, forKey: key)
    }
    
    func getInt(forKey key: String) -> Int {
        let value = UserDefaults.standard.object(forKey: key) as? Int
        return value ?? -1
    }
    
    func setBool(_ value: Bool, forKey key: String) {
        UserDefaults.standard.set(value, forKey: key)
    }
    
    func getBool(forKey key: String) -> Bool {
        let value = UserDefaults.standard.object(forKey: key) as? Bool
        return value ?? false
    }
    
    // 保存对话记录为JSON格式
    func saveChatMessage(role: Bool, content: String) {
        var chatMessages = UserDefaults.standard.array(forKey: "chatMessages") as? [[String: String]] ?? []
        let newMessage = [
            "role": role ? "user" : "assistant",
            "content": content
        ]
        chatMessages.append(newMessage)
        UserDefaults.standard.set(chatMessages, forKey: "chatMessages")
    }
    
    // 获取保存的对话记录
    func getChatMessages() -> [[String: String]] {
        let chatMessages = UserDefaults.standard.array(forKey: "chatMessages") as? [[String: String]] ?? []
        return chatMessages
    }
    
    func getChatMessagesJSON() -> String {
           let chatMessages = getChatMessages()
           if let jsonData = try? JSONSerialization.data(withJSONObject: chatMessages, options: .prettyPrinted) {
               return String(data: jsonData, encoding: .utf8) ?? "[]"
           }
           return "[]"
       }
    func clearChatMessages() {
            UserDefaults.standard.removeObject(forKey: "chatMessages")
        }
    func isChatMessageCountGreaterThanTen() -> Bool {
            let chatMessages = getChatMessages()
        print("count",chatMessages.count)
            return chatMessages.count < 10
        }
}
